from flask import Flask, request, g
from flask_cors import CORS
from blueprint.static_blueprint import static_blueprint
from blueprint.baby_blueprint import baby_blueprint
from blueprint.baby_sleep_records_blueprint import records_blueprint
from blueprint.user_blueprint import user_blueprint
from util.jwt_util import verify_jwt_token


#
#这是整个用户端的入口文件，运行此文件即可启动整个用户端服务
#用户端所有功能都通过调用本服务来完成
#


app = Flask(__name__)
CORS(app)


# 全局拦截器
@app.before_request
def log_request():
    # 排除预检请求
    if request.method == 'OPTIONS':
        return
    print(f"请求相对路径{request.path}")
    if not exclude_paths(request.path):  # 排除 OPTIONS 请求
        print(f"拦截处理：{request.url}")
        auth_header = request.headers.get('Authorization')
        print(f"Authorization: {auth_header}")
        if auth_header and auth_header.startswith('Bearer'):
            token = auth_header.split(' ')[1]  # 分割 Bearer令牌并获取第二部分
            decoded_payload = verify_jwt_token(token)
            g.user = decoded_payload  # 将用户信息存储在g对象中
        else:
            g.user = None  # 如果没有有效的Bearer令牌，将用户信息设为None


# 拦截器排除路径
def exclude_paths(path):
    return (path.startswith('/user/login') or
            path.startswith('/user/register') or
            path.startswith('/image'))


app.register_blueprint(static_blueprint, url_prefix='/image')
app.register_blueprint(baby_blueprint, url_prefix='/baby')
app.register_blueprint(records_blueprint, url_prefix='/records')
app.register_blueprint(user_blueprint, url_prefix='/user')

if __name__ == '__main__':
    #启动用户端服务
    app.run()
    print("用户端服务已经启动......")


